#!/bin/bash

function startOrRestartService()
{
	domain=$1
	service=$2
	if [[ $domain == system* ]]; then
		plistPath="/Library/LaunchDaemons"
	elif [[ $domain == gui/* ]]; then
		plistPath="/Library/LaunchAgents"
	fi
	startCmd="/bin/launchctl bootstrap $domain $plistPath/$service.plist"
	restartCmd="/bin/launchctl kickstart -k $domain/$service"
	isLoaded=`/bin/launchctl print $domain/$service | wc -l`
	if [ $isLoaded -gt "0" ]; then
		echo "Restarting Service: '$restartCmd'"
		eval $restartCmd || exit 1
	else
		echo "Starting Service: '$startCmd'"
		eval $startCmd || exit 1
	fi
}

# Load PrjFSKext if it is not loaded already
# PrjFSKext is an IOKit kext and should get automatically loaded 
# by macOS after install. But the system does not seem to auto-load it
# consistently after every install. The code below checks if it has
# been auto-loaded. If not, it will attempt to load it.
# The BundleID of the Kext(ProjFS.Mac/PrjFS.xcodeproj) is defined in
# ProjFS.Mac/PrjFS.xcodeproj project.
KEXTBUNDLEID="org.vfsforgit.PrjFSKext"
KEXTPATH="/Library/Extensions/PrjFSKext.kext"
kextstatCmd="/usr/sbin/kextstat -l -b $KEXTBUNDLEID"
kextstatOutput=$(eval $kextstatCmd)
if [[ -z "${kextstatOutput// }" ]]; then
# load the kext using kextload command. Installer is run as the
# admin user, so we already have required privileges. In case load
# still fails, then exit 1. This will cause the installer to display
# an installation failed error message.
    loadCmd="/sbin/kextload \"$KEXTPATH\""
    echo $loadCmd
    eval $loadCmd || exit 1
else
    echo "$kextstatCmd returned non-zero output. This might possibly indicate an error."
    echo "$kextstatOutput"
fi

startOrRestartService "system" "org.vfsforgit.prjfs.PrjFSKextLogDaemon"

# Load Launch Agents in all active User sessions
# There will be one loginwindow instance for each logged in user, 
# get its uid (this will correspond to the logged in user's id.) 
# Then use launchctl bootstrap gui/uid to auto load the Service 
# for each user.
declare -a launchAgents=(
    "org.vfsforgit.usernotification"
    "org.vfsforgit.service"
)
for uid in $(ps -Ac -o uid,command | grep -iw "Finder" | awk '{print $1}'); do
    for nextLaunchAgent in "${launchAgents[@]}"; do
        startOrRestartService "gui/$uid" $nextLaunchAgent
    done
done 
